package com.atguigu.mySmartCampus.controller;

import com.atguigu.mySmartCampus.Service.AdminService;
import com.atguigu.mySmartCampus.Service.StudentService;
import com.atguigu.mySmartCampus.Service.TeacherService;
import com.atguigu.mySmartCampus.entity.Admin;
import com.atguigu.mySmartCampus.entity.LoginForm;
import com.atguigu.mySmartCampus.entity.Student;
import com.atguigu.mySmartCampus.entity.Teacher;
import com.atguigu.mySmartCampus.util.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@Api(tags = "系统")
@RequestMapping("/sms/system")
public class SystemController {

//本来我以为不用装配  没想到  所有的都要装配

    @Autowired
    private AdminService adminService;

    @Autowired
    private StudentService studentService;

//    private TeacherService teacherService;
    @Autowired
    private TeacherService teacherService;

    @ApiOperation("登录")
    @PostMapping("/login")
    public Result login(@ApiParam("登录的表单") @RequestBody LoginForm loginForm, HttpServletRequest req) {
        HttpSession httpSession = req.getSession();
        String sessionVerifyCode = (String) httpSession.getAttribute("verifiCode");
        String loginVerifyCode = loginForm.getVerifiCode();
        System.out.println("SystemController.login"
                +"\n--> loginForm=" +loginForm
                +"\n--> sessionVerifyCode=" +sessionVerifyCode
                +"\n--> loginVerifyCode=" +loginVerifyCode
                );
        if (sessionVerifyCode == null||sessionVerifyCode.equals("")  ) {
            return Result.fail().message("服务器验证码失效");
        }
        if ( loginVerifyCode == null||loginVerifyCode.equals("") ) {
            return Result.fail().message("浏览器验证码失效");
        }
        if (!sessionVerifyCode.equalsIgnoreCase(loginVerifyCode)) {
            return Result.fail().message("验证码不一致 可以忽略大小写");
        }
        httpSession.removeAttribute("verifiCode");

        Map<String, Object> map = new LinkedHashMap();
        Integer userType = loginForm.getUserType();
        switch (userType) {
            case 1:
                try {
                    Admin admin = adminService.login(loginForm);
                    if (admin != null) {
                        //..return Result.ok(admin);
                        map.put("token", JwtHelper.createToken(admin.getId().longValue(), userType));
                    } else {
                        throw new RuntimeException("管理员账号错误");
                    }
                    return Result.ok(map);
                } catch (RuntimeException e) {
                    e.printStackTrace();
                    return Result.fail().message(e.getMessage());
                }
            case 2:
                try {
                    Student student = studentService.login(loginForm);
                    if (student != null) {
                        //..return Result.ok(admin);
                        map.put("token", JwtHelper.createToken(student.getId().longValue(), userType));
                    } else {
                        throw new RuntimeException("学生账号错误");
                    }
                    return Result.ok(map);
                } catch (RuntimeException e) {
                    e.printStackTrace();
                    return Result.fail().message(e.getMessage());
                }

            case 3:
                try {
                    Teacher teacher = teacherService.login(loginForm);
                    if (teacher != null) {
                        //..return Result.ok(admin);
                        map.put("token", JwtHelper.createToken(teacher.getId().longValue(), userType));
                    } else {
                        throw new RuntimeException("老师账号错误");
                    }
                    return Result.ok(map);
                } catch (RuntimeException e) {
                    e.printStackTrace();
                    return Result.fail().message(e.getMessage());
                }
        }
        return Result.fail().message("查无此用户");
    }

    @ApiOperation("更新密码")
    @PostMapping("/updatePwd/{oldPwd}/{newPwd}")
    public Result updatePwd(@ApiParam("token") @RequestHeader("token") String token,
                            @ApiParam("旧密码") @PathVariable String oldPwd,
                            @ApiParam("新密码") @PathVariable String newPwd
    ) {
        //..boolean isExiprtion = JWTHelper.isExiprtion(token);
        boolean isExpiration = JwtHelper.isExpiration(token);
        if (isExpiration) {
            return Result.fail().message("token失效，请重新登录后改密码");
        }
        Long userId = JwtHelper.getUserId(token);
        Integer userType = JwtHelper.getUserType(token);

        oldPwd = MD5.encrypt(oldPwd);
        newPwd = MD5.encrypt(newPwd);

        switch (userType) {
            case 1:
                QueryWrapper<Admin> qw = new QueryWrapper();
                qw.eq("id", userId.intValue());
                qw.eq("password", oldPwd);
                Admin admin = adminService.getOne(qw);
                if (admin != null) {
                    //..admin.setPassword(MD5.encrypt(admin.getPassword()));
                    admin.setPassword(newPwd);
                    adminService.saveOrUpdate(admin);
                } else {
                    return Result.fail().message("登录失败");
                }

            case 2:
                QueryWrapper<Student> qw2 = new QueryWrapper();
                qw2.eq("id", userId.intValue());
                qw2.eq("password", oldPwd);
                Student student = studentService.getOne(qw2);
                if (student != null) {
                    //..admin.setPassword(MD5.encrypt(admin.getPassword()));
                    student.setPassword(newPwd);
                    studentService.saveOrUpdate(student);
                } else {
                    return Result.fail().message("登录失败");
                }

            case 3:
                QueryWrapper<Teacher> qw3 = new QueryWrapper();
                qw3.eq("id", userId.intValue());
                qw3.eq("password", oldPwd);
                Teacher teacher = teacherService.getOne(qw3);
                if (teacher != null) {
                    //..admin.setPassword(MD5.encrypt(admin.getPassword()));
                    teacher.setPassword(newPwd);
                    teacherService.saveOrUpdate(teacher);
                } else {
                    return Result.fail().message("登录失败");
                }
        }
        return Result.ok();
    }


    @ApiOperation("文件上传")
    @PostMapping("/headerImgUpload")
    public Result headerImgUpload(@ApiParam("文件") @RequestPart("multipartFile") MultipartFile multipartFile, HttpServletRequest req) {
        String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase();
//      String originalFileName = multipartFile.getOriginalFileName();
        String originalFileName = multipartFile.getOriginalFilename();
        int index = originalFileName.lastIndexOf(".");
        String fileName = uuid.concat(originalFileName.substring(index));


//        String portraitPath = "C:/code/mySmartCampus/target/classes/public/upload/".concat(fileName);
        //改成自己的路径
        String portraitPath = "C:/Users/Administrator/IdeaProjects/smart-school/target/classes/public/upload/".concat(fileName);
        //old code
//        String portraitPath = "C:/Users/Administrator/IdeaProjects/smart-school/src/main/resources/public/upload/".concat(fileName);

        try {
            multipartFile.transferTo(new File(portraitPath));
        } catch (IOException e) {
            e.printStackTrace();
        }

        String path = "upload/".concat(fileName);
        return Result.ok(path);
    }

    @ApiOperation("通过token口令获取当前登录的用户信息")
    @GetMapping("/getInfo")
    public Result getInfoByToken(@ApiParam("token") @RequestHeader String token) {
        boolean isExpiration = JwtHelper.isExpiration(token);
        if (isExpiration) {
            return Result.build(null, ResultCodeEnum.TOKEN_ERROR);
        }

        Long userId = JwtHelper.getUserId(token);
        Integer userType = JwtHelper.getUserType(token);
        System.out.println("SystemController.getInfoByToken"
                +"\n--> token= " +token
                +"\n--> userid= " +userId
                +"\n--> userType= " +userType
                );
        Map<String, Object> map = new LinkedHashMap();
        switch (userType) {

            case 1:
                Admin admin = adminService.getAdminById(userId);
                map.put("user", admin);
                map.put("userType", userType);
                break;
            case 2:
                Student student = studentService.getStudentById(userId);
                map.put("user", student);
                map.put("userType", userType);
                break;
            case 3:
                Teacher teacher = teacherService.getTeacherById(userId);
                map.put("user", teacher);
                map.put("userType", userType);
                break;
        }
        return Result.ok(map);
    }

//http://localhost:9001/sms/system/getVerifiCodeImage?t=1686177943647
    @GetMapping("/getVerifiCodeImage")
    public Result getVerifyCode(HttpServletRequest req, HttpServletResponse resp) {
//        BufferedImage bi = CreateVerifyCodeImg.getVerifyCodeImage();
        BufferedImage bi = CreateVerifyCodeImg.getVerifyCodeImg();
        String verifyCode = new String(CreateVerifyCodeImg.getVerifyCode());
        HttpSession session = req.getSession();


        session.setAttribute("verifiCode", verifyCode);
        System.out.println("SystemController.getVerifyCode"
                +"\n-->session getAttribute verifiCode= " + session.getAttribute("verifiCode")
                +"\n-->verifyCode = " + verifyCode
        );
        try {
            ImageIO.write(bi, "JPEG", resp.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }

        return Result.ok();
    }

}